const { PrismaClient } = require('@prisma/client');

const prisma = new PrismaClient();

async function addAuditFields() {
  try {
    console.log('开始添加审核字段...');

    // 添加审核状态枚举
    await prisma.$executeRaw`
      ALTER TABLE listings 
      ADD COLUMN audit_status ENUM('PENDING', 'APPROVED', 'REJECTED') DEFAULT 'PENDING' AFTER expires_at
    `;
    console.log('✓ 添加审核状态字段');

    // 添加审核管理员ID
    await prisma.$executeRaw`
      ALTER TABLE listings 
      ADD COLUMN audit_admin_id INT UNSIGNED NULL AFTER audit_status
    `;
    console.log('✓ 添加审核管理员ID字段');

    // 添加审核时间
    await prisma.$executeRaw`
      ALTER TABLE listings 
      ADD COLUMN audit_time TIMESTAMP NULL AFTER audit_admin_id
    `;
    console.log('✓ 添加审核时间字段');

    // 添加审核备注
    await prisma.$executeRaw`
      ALTER TABLE listings 
      ADD COLUMN audit_comment TEXT NULL AFTER audit_time
    `;
    console.log('✓ 添加审核备注字段');

    // 添加自动发布时间
    await prisma.$executeRaw`
      ALTER TABLE listings 
      ADD COLUMN auto_publish_at TIMESTAMP NULL AFTER audit_comment
    `;
    console.log('✓ 添加自动发布时间字段');

    // 添加外键约束
    await prisma.$executeRaw`
      ALTER TABLE listings 
      ADD CONSTRAINT fk_listings_audit_admin_id 
      FOREIGN KEY (audit_admin_id) REFERENCES administrators(id) ON DELETE SET NULL
    `;
    console.log('✓ 添加外键约束');

    // 添加索引
    await prisma.$executeRaw`CREATE INDEX idx_audit_status ON listings(audit_status)`;
    console.log('✓ 添加审核状态索引');

    await prisma.$executeRaw`CREATE INDEX idx_auto_publish ON listings(auto_publish_at)`;
    console.log('✓ 添加自动发布时间索引');

    console.log('所有审核字段添加完成！');

  } catch (error) {
    console.error('添加审核字段失败:', error);
    if (error.message.includes('Duplicate column name')) {
      console.log('字段可能已经存在，跳过...');
    } else if (error.message.includes('Duplicate key name')) {
      console.log('索引可能已经存在，跳过...');
    } else {
      throw error;
    }
  } finally {
    await prisma.$disconnect();
  }
}

addAuditFields();
